import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch(err => {})
};

Vue.use(VueRouter)

const routes = [
  // 重定向
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      activenum: 0,
      isShowTabbar: true
    },
    children: [{
      path: '/home/searchPopup',
      name: 'SearchPopup',
      component: () => import( /* webpackChunkName: "SearchPopup" */ '../views/SearchPopup.vue')
    }]
  },
  {
    path: '/topic',
    name: 'Topic',
    component: () => import( /* webpackChunkName: "Topic" */ '../views/Topic.vue'),
    meta: {
      activenum: 1,
      isShowTabbar: true
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: () => import( /* webpackChunkName: "Category" */ '../views/Category.vue'),
    meta: {
      activenum: 2,
      isShowTabbar: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: () => import( /* webpackChunkName: "Cart" */ '../views/Cart.vue'),
    meta: {
      activenum: 3,
      isShowTabbar: true
    }
  },
  {
    path: '/user',
    name: 'User',
    component: () => import( /* webpackChunkName: "User" */ '../views/User.vue'),
    meta: {
      activenum: 4,
      isShowTabbar: true
    }
  },
  {
    path: '/productDetail',
    name: 'ProductDetail',
    component: () => import( /* webpackChunkName: "ProductDetail" */ '../views/ProductDetail.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//路由守卫
router.beforeEach((to, from, next) => {
  // console.log(to);要去往的路由对象
  // console.log(from);从哪里出发的路由对象
  // console.log(next);next 代表放行，可以顺利通往要去的路由，如果不写next()，就不能去往想去的路由
  let token = localStorage.getItem('token')
  if (to.path == '/cart') {
    //判断有没有登陆，判断token是否存在
    if (token) {
      next()
    } else {
      //表示没有登陆
      Vue.prototype.$toast('请先登陆');
      setTimeout(() => {
        next('/user')
      }, 1111)

    }
  }
  next(); //这个不能不写！！！
})

export default router